// miniprogram/pages/addApproval/addApproval.js
import ProgressConstruction from "../../core/ProgressConstruction.js";
var util = require('../../core/guid.js')
import FileInfomation from "../../core/FileInfomation.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    projects: getApp().globalData.projects,
    selectProject: getApp().globalData.nowPrj,
    type: null,

    def_inout_list: null,
    ruletemplate_list: null,
    roletemplate_list: null,
    user_list: null,

    newOne: null,

    //
    scrollTop: 0,
    toggle2: false,
    actions0: [
      {
        name: '新增',
        color: '#fff',
        fontsize: '20',
        width: 100,
        icon: 'add',
        background: 'green'
      },
      {
        name: '删除',
        width: 100,
        color: 'white',
        fontsize: '20',
        icon: 'delete',
        background: 'red'
      }
    ],
    actions1: [
      {
        name: '新增',
        color: '#fff',
        fontsize: '20',
        width: 100,
        icon: 'add',
        background: 'green'
      }
    ],
    filemodel: {
      tempImgFilePaths: [],
      tempVideoFilePaths: [],
      tempSoundFilePaths: [],
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let newOne = ProgressConstruction.newInstance();
    newOne.Time="请选择";
    this.setData({
      newOne: newOne,
      projects: getApp().globalData.projects,
      selectProject: getApp().globalData.nowPrj,
      type: options.type,
      def_inout_list: getApp().globalData.sys.def_inout_list.filter(x => !x.IsIncome),
      ruletemplate_list: getApp().globalData.sys.ruletemplate_list.filter(x => x.TargetType_Guid == options.type),
      roletemplate_list: getApp().globalData.sys.roletemplate_list,
      user_list: getApp().globalData.sys.user_list,
    })

    console.log(this.data.user_list)
  },
  bindTimeChange(e) {
    let newOne = this.data.newOne;
    newOne.Time = e.detail.value;
    this.setData({ newOne: newOne });
  },
  bindApproval_Desc(e) {
    let newOne = this.data.newOne;
    newOne.Pos = e.detail.value;
    this.setData({ newOne: newOne });
  },
  bindApproval_Progress(e) {
    let newOne = this.data.newOne;
    newOne.Progress = e.detail.value;
    this.setData({ newOne: newOne });
  },
  getGUID() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid
  },
  uploadRecord(objlist) {
    let that = this;
    let pList = [];
    objlist.forEach(x => {
      pList.push(x.create());
    })
    Promise.all(pList)
      .then(
        res => {
          console.log("files", res);
          let list = [];
          res.forEach(x => list.push(x.GuidID));
          let str = list.join(",");
          let newOne = this.data.newOne;
          newOne.Files = str;
          newOne.Time+=" 00:00:00"
          newOne.create()
            .then(
              res4 => {
                console.log("success", res4);
                var pages = getCurrentPages();
                var prevPage = pages[pages.length - 2];
                prevPage.onRefresh();
                wx.navigateBack({
                  delta: 1,
                })
              }
            )
        }
      )
  },
  uploadOne(index, tot, imgs, objlist) {
    let that = this;
    let guid = this.getGUID();
    let filename = "sp/" + guid + ".png";
    objlist.push(new FileInfomation({
      "Source": "oss",
      "Param": filename,
      "RawFileName": "现场采集 第" + (index + 1) + "张.png",
      "Size": imgs[index].size,
    }));
    let task = wx.uploadFile({
      url: 'https://zgxtfile.chenxifunds.com/',
      filePath: imgs[index].path,
      name: 'file',
      formData: {
        name: imgs[index].path,
        key: filename,
        policy: "eyJleHBpcmF0aW9uIjoiMjAzMC0wMS0wMVQxMjowMDowMC4wMDBaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF1dfQ==",
        OSSAccessKeyId: "LTAI4G4MkoVW2FiUubiuk2Fo",
        success_action_status: 200,
        signature: "doJrPoNRbgmQSyDnw6sVzWLS/iM=",
      },
      success: function (res) {
        console.log("task finish", index);
        if (index < tot - 1) {
          that.uploadOne(index + 1, tot, imgs, objlist);
        } else {
          if (index == tot - 1) {
            that.uploadRecord(objlist);
          }
        }
      }
    })
    task.onProgressUpdate((res) => {
      console.log("task ", index, res.progress);
    });
  },
  submit() {
    console.log(this.data.newOne);
    console.log(this.data.filemodel);
    let objlist = [];
    this.uploadOne(0, this.data.filemodel.tempImgFilePaths.length, this.data.filemodel.tempImgFilePaths, objlist);   //上传照片
  },
  cancel() {
    wx.navigateBack({
      delta: 1,
    })
  },
  changeFileData(model) {
    this.setData(
      {
        filemodel: model
      }
    )
    console.log("更新", model);
  },
  checkboxChange(e) {
    let newOne = this.data.newOne;
    newOne.UseSeal = !newOne.UseSeal;
    this.setData({
      newOne: newOne
    })
  },
  addFile() {

    wx.navigateTo({
      url: '../addFile/addFile?model=' + JSON.stringify(this.data.filemodel),
      success: function () { }, //成功后的回调；
    })
  },
  handlerCloseButton(e) {
    let objID = e.currentTarget.dataset.ii;
    let btnIndex = e.detail.index;
    let newOne = this.data.newOne;
    let obj = newOne.approvalProcesses[objID];
    if (obj.canBeDelete) {
      if (btnIndex == 0) {
        //新增
        newOne.approvalProcesses.splice(objID + 1, 0, ApprovalProcess.newSubInstance());
      }
      else {
        //删除
        let list = [];
        for (let i = 0; i < newOne.approvalProcesses.length; i++) {
          if (i != objID) {
            list.push(newOne.approvalProcesses[i]);
          }
        }
        newOne.approvalProcesses = list;
      }
    } else {
      if (btnIndex == 0) {
        //新增
        newOne.approvalProcesses.splice(objID + 1, 0, ApprovalProcess.newSubInstance());
      }
    }
    this.setData({ newOne: newOne });
    this.setData({
      toggle2: this.data.toggle2 ? false : true
    });
  },
  addProcess() {
    let newOne = this.data.newOne;
    newOne.approvalProcesses.unshift(ApprovalProcess.newSubInstance());
    this.setData({ newOne: newOne });
  },
  ruleChangedClick(e) {
    let that = this;
    let newOne = this.data.newOne;
    newOne.ApprovalRule = this.data.ruletemplate_list[e.detail.value].GuidID;
    newOne.ApprovalRuleName = this.data.ruletemplate_list[e.detail.value].Remark;

    //process
    let ruleTemplate = this.data.ruletemplate_list.find(x => x.GuidID == newOne.ApprovalRule);
    newOne.approvalProcesses = [];
    if (ruleTemplate.ruleResultTemplates.length == 0) {
      this.setData({
        newOne: newOne
      })
      return;
    }
    for (let i = 0; i < ruleTemplate.ruleResultTemplates.length; i++) {
      let now = ruleTemplate.ruleResultTemplates[i];
      let One = ApprovalProcess.newSubInstance();
      One.canBeDelete = false;
      let role = that.data.roletemplate_list.find(x => x.GuidID == now.Ref_Role_Guid);
      One.Remark = role.Name;
      One.aList = [];
      One.has = false;
      //找个合适的可选列表
      let userRoles = getApp().globalData.sys.userrole_list.filter(x => x.Ref_RoleTemplate_Guid == role.GuidID);
      if (role.RoleTemplateType == "department") {
        userRoles.forEach(x => {
          One.aList.push(getApp().globalData.sys.user_list.find(y => y.GuidID == x.Ref_User_Guid));
          One.has = true;
        })
      } else {
        userRoles.filter(x => x.Param == getApp().globalData.nowPrj.GuidID).forEach(x => {
          One.aList.push(getApp().globalData.sys.user_list.find(y => y.GuidID == x.Ref_User_Guid));
          One.has = true;
        })
      }
      //
      if (One.aList.length == 0) {
        One.aList = null;
      }
      newOne.approvalProcesses.push(One);
      this.setData({
        newOne: newOne
      })
      console.log(this.data.newOne)
    }
  },
  typeChangedClick(e) {
    let newOne = this.data.newOne;
    newOne.Pay_Type_Guid = this.data.def_inout_list[e.detail.value].GuidID;
    newOne.inOutDefName = this.data.def_inout_list[e.detail.value].Type;
    this.setData({
      newOne: newOne
    })
  },
  processChangedClick(e) {
    let objID = e.currentTarget.dataset.ii;
    let valueID = e.detail.value;
    let newOne = this.data.newOne;
    let obj = newOne.approvalProcesses[objID];
    if (obj.aList) {
      obj.Ref_Person_Guid = obj.aList[valueID].PerInfoID;
      obj.personnelInfoName = obj.aList[valueID].Name;
    } else {
      obj.Ref_Person_Guid = this.data.user_list[valueID].PerInfoID;
      obj.personnelInfoName = this.data.user_list[valueID].Name;
    }
    this.setData({
      newOne: newOne
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onChange(event) {
    console.log(event.detail, 'click right menu callback data')
  },
  //页面滚动执行方式
  onPageScroll(event) {
    this.setData({
      scrollTop: event.scrollTop
    })
  }
})